package com.caisejingyu.whales.common.api;

import android.support.annotation.NonNull;


import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.caisejingyu.whales.common.AppConfig;
import com.caisejingyu.whales.common.api.interceptor.BaseInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * ApiManager
 *
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public class ApiManager implements IApiManager {

    private Retrofit mDefaultRetrofit;
    private OkHttpClient mDefaultOkHttpClient;

    private static IApiManager sApiManager;

    public static IApiManager getInstance() {
        if (sApiManager == null) {
            sApiManager = new ApiManager();
        }
        return sApiManager;
    }

    @Override
    public OkHttpClient getDefaultOkHttpClient() {
        if (mDefaultOkHttpClient == null) {
            initDefaultOkHttpClient();
        }
        return mDefaultOkHttpClient;
    }

    @Override
    public OkHttpClient.Builder createDefaultOkHttpBuilder() {
        ApiConfig apiConfig = ApiConfig.getInstance();
        // 配置OkHttp参数
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        if (AppConfig.getInstance().isDebugMode()) {
            // 增加log日志
            okHttpBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        okHttpBuilder.connectTimeout(apiConfig.getConnectTimeout(), TimeUnit.SECONDS)
                .readTimeout(apiConfig.getReadTimeout(), TimeUnit.SECONDS)
                .writeTimeout(apiConfig.getWriteTimeout(), TimeUnit.SECONDS)
                .retryOnConnectionFailure(apiConfig.isRetryOnConnectionFailure());
        return okHttpBuilder;
    }

    @Override
    public <T> T getApi(@NonNull Class<T> api) {
        if (mDefaultRetrofit == null) {
            initDefaultRetrofit();
        }
        return mDefaultRetrofit.create(api);
    }

    @Override
    public <T> T getApi(@NonNull Retrofit retrofit, @NonNull Class<T> api) {
        return retrofit.create(api);
    }

    private void initDefaultRetrofit() {
        mDefaultRetrofit = new Retrofit.Builder()
                .client(getDefaultOkHttpClient())
                .baseUrl(ApiConfig.getInstance().getBaseUrl())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    private void initDefaultOkHttpClient() {
        mDefaultOkHttpClient = createDefaultOkHttpBuilder().addInterceptor(new BaseInterceptor(ApiConfig.getInstance())).build();
    }


}
